<?php


namespace app\common\service\supplier;


use app\common\facade\auth\Auth;
use app\model\AgentChannel;
use app\model\CouponBrand;
use app\model\CouponBrandType;
use app\model\CouponProductChannel;
use app\model\PageSetting;
use app\model\ChannelServDiscount;

class JumpTypeService
{
    /**
     * @note 顶部推荐new
     * @access public
     * @method get
     * @author ymzhang
     * @date 2022-09-01
     * @time 17:45
     * @returns
     */
    public function getJumpConfig($params)
    {
        $params['status'] = PageSetting::STATUS_ACTIVE;
        $pageSetting = new PageSetting();
        $channel = $params['channel'] ?? '';
        if ($channel == AgentChannel::YMHC_ADMIN_CHANNEL) {
            $params['agent_id'] = 0;
            $params['source'] = PageSetting::SOURCE_SYSTEM;
        }
        $pageSetting->updateMeituanCoupon();
        //1.首页轮播图 todo 如果是品牌权益的，头部和中间轮播图一起获取
        $params['sub_category'] = PageSetting::SUB_CATEGORY_SYLBT;
        $lunBo = $pageSetting->getList($params);
        if (!$lunBo->isEmpty()) {
            if ($channel == AgentChannel::YMHC_ADMIN_CHANNEL) {//ymhcadmin
                $lunBo = $lunBo->toArray();
            } else {
                $lunBo = $this->checkRight($lunBo->toArray());
            }
            if ($lunBo) {
                $lunBo = array_values($lunBo);
            }
        }
        unset($params['sub_category']);

        //2.查询豆腐块
        $tofu = [];
        //todo 只有品牌权益才有豆腐块
        if ($params['type'] == PageSetting::TYPE_COUPON) {
            $params['sub_category'] = PageSetting::SUB_CATEGORY_DFK;
            $tofu = $pageSetting->getList($params);
            if (!$tofu->isEmpty()) {
                if ($channel == AgentChannel::YMHC_ADMIN_CHANNEL) {
                    $tofu = $tofu->toArray();
                } else {
                    $tofu = $this->checkRight($tofu->toArray());
                }
                if ($tofu) {
                    $tofu = array_values($tofu);
                }
            }
            unset($params['sub_category']);
        }

        //3.查询金刚区
        $params['sub_category'] = PageSetting::SUB_CATEGORY_SYJGQ;
        $king = $pageSetting->getList($params);
        //if (!$king->isEmpty() && $channel != AgentChannel::YMHC_ADMIN_CHANNEL) {
        if (!$king->isEmpty()) {
            if ($channel == AgentChannel::YMHC_ADMIN_CHANNEL) {
                $king = $king->toArray();
            } else {
                $king = $this->checkRight($king->toArray());
            }
            //todo 外卖系统和本地生活的金刚区才去计算最低折扣
            //if ($king && in_array($params['type'],[PageSetting::TYPE_TACKOUT,  PageSetting::TYPE_LOCAL_LIFE])) {
            if ($king) {
                foreach ($king as $key => $pageSetting) {
                    $ext_data = $pageSetting['ext_data'];
                    //品牌权益
                    if ($ext_data['jump_type'] == 5 && isset($ext_data['brand_id']) && $brand_id = $ext_data['brand_id']) {
                        /**
                         * @var CouponBrand $brand
                         */
                        $brand = CouponBrand::query()
                            ->with(['productChannel' => function ($query) {
                                $query->availableSale();
                            }])

                            ->where('id', $brand_id)->find()->append(['sale_price_discount']);
                        $brand->productChannelObj = $brand->productChannel;

                        $brand2 = clone  $brand;

                        $productData = collect($brand2->productChannel)->toArray();

//
                        foreach ($productData as $key2 =>$item2){
                            /**@var CouponProductChannel $productChannel */
                            $couponBrandChannel = CouponProductChannel::query()->where('id',$item2['id'])->find();

                            if (empty($couponBrandChannel)
                                || empty($couponBrandChannel->product)
                                || empty($couponBrandChannel->product->brand_type)
                                || $couponBrandChannel->product->brand_type->status == CouponBrandType::STATUS_CLOSE){
                                unset($productData[$key2]);
                            }

                        }
                        $productData = array_values($productData);

                        if (collect($productData)->where('shelf_state',CouponProductChannel::SHELF_STATE_SZ)->where('relate_state',CouponProductChannel::RELETE_STATE_YPP)->isEmpty()) {
                            unset($king[$key]);
                            continue;
                        }
                        $king[$key]['sale_price_discount'] = $brand->sale_price_discount;
                        $king[$key]['productChannel'] = $brand->productChannel;
                    }
                }
            }
            if ($king) {
                $king = array_values($king);
            }
        }

        return success('success', compact('lunBo', 'tofu', 'king'));
    }

    /**
     * @note 前端跳转类型转换成后端统一的服务类型
     * @access public
     * @author ymzhang
     * @returns mixed
     */
    public function exchangeServTypeByJumpType($jump_type)
    {
        if ($jump_type == 0) {
            return 0;
        }
        $data = [
            1 => PRODUCT_ELE_SERV,             //饿了么
            2 => PRODUCT_MEITUAN_TAKEOUT_SERV, //美团外卖
            3 => PRODUCT_METUAN_SERV,          //美团到店---吃喝玩乐
            4 => PRODUCT_FILM_SERV,            //电影
            5 => PRODUCT_COUPON_SERV,          //权益
            6 => PRODUCT_MOBILE_CPS_SERV,      //话费
            9 => PRODUCT_TRAVEL_OIL_SERV,      //出行加油
            10 => PRODUCT_AROUND_SHOP_SERV,    //周边游
            11 => PRODUCT_FOOD_SHOP_SERV,      //连锁餐饮
            15 => PRODUCT_MOBILE_CPS_SERV      //CPS话费
        ];
        //约定自15CPS话费后，跳转类型就是服务类型,后面不需要加一种跳转类型就在这边加
        if (in_array($jump_type, [
                PRODUCT_TRAVEL_OIL_SERV,
                PRODUCT_AROUND_SHOP_SERV,
                PRODUCT_FOOD_SHOP_SERV,
                PRODUCT_ELE_SERV,
                PRODUCT_MEITUAN_TAKEOUT_SERV,
                PRODUCT_MOBILE_CPS_SERV
            ]) || ($jump_type > 15 && $jump_type < 99)) {
            return $jump_type;
        }
        return $data[$jump_type] ?? '';
    }

    /**
     * @note 权限判断
     * @access public
     * @author ymzhang
     * @returns mixed
     */
    public function checkRight($list)
    {
        //查询服务权限
        $channelServ = (new ChannelServDiscount())->getRealServ(Auth::channelId(), Auth::agentId(), input('template_url'));
        if (empty($channelServ)) {
            return fail('尚未开通产品权限');
        }
        $channel_serv = array_values($channelServ);
        return array_filter($list, function ($data) use ($channel_serv) {
            $jump_type = $data['ext_data']['jump_type'] ?? '';
            $serv_type = $this->exchangeServTypeByJumpType($jump_type);
            if ($serv_type != 0) {
                //$channel_serv = [4 ,5];
                if (!in_array($serv_type, $channel_serv)) {
                    return false;
                }
            }
            return true;
        });
    }
}